$(function() {
 // Handler for .ready() called.
	console.log('ready');

	//grabs list of buildings
	//Bind to the create so the page gets updated with the listing
	$('#search').bind('pagebeforeshow',function(event, ui){
		console.log('pagebeforeshow');
	
		//Remove the old rows
		$( ".buildinglist_row" ).remove();
		
		//JQuery Fetch The New Ones
		$.ajax({
			url: "api/buildings",
			dataType: "json",
	        async: false,
	        success: function(data, textStatus, jqXHR) {
				console.log(data);
	        	//Create The New Rows From Template
	        	$( "#buildinglist_row_template" ).tmpl( data ).appendTo( "#buildinglist" );
	        },
	        error: ajaxError
		});
		
		$('#buildinglist').listview('refresh'); /* refreshes all the rows so 'page before show' works*/
	});
	
	//grabs list of classrooms within building
	//Bind to the create so the page gets updated with the listing
	$('#viewbuilding').bind('pagebeforeshow',function(event, ui){
		console.log('pagebeforeshow');
	
		//Remove the old rows
		$( ".classroomlist_row" ).remove();
		
		//Get the building id from the fragment section of the url
		var building_id =  $.url().fparam("building_id");
		
		//JQuery Fetch The New Ones
		$.ajax({
			url: "api/buildings/"+building_id+"/classrooms/",
			dataType: "json",
	        async: false,
	        success: function(data, textStatus, jqXHR) {
				console.log(data);
	        	//Create The New Rows From Template
	        	$( "#classroomlist_row_template" ).tmpl( data ).appendTo( "#classroomlist" );
	        },
	        error: ajaxError
		});
		
		$('#classroomlist').listview('refresh'); // refreshes all the rows so 'page before show' works
	});
});

/******************************************************************************/

function ajaxError(jqXHR, textStatus, errorThrown){
	console.log('ajaxError '+textStatus+' '+errorThrown);
	$('#error_message').remove();
	$("#error_message_template").tmpl( {errorName: textStatus, errorDescription: errorThrown} ).appendTo( "#error_dialog_content" );
	$.mobile.changePage($('#error_dialog'), {
		transition: "pop",
		reverse: false,
		changeHash: false
	});
}
